package com.uwlaser.utils;

import cn.hutool.http.*;
import com.alibaba.fastjson.JSONObject;
import com.uwlaser.http.exception.HttpCodeErrorException;
import com.uwlaser.http.exception.HttpException;
import com.uwlaser.http.exception.HttpTimeoutException;

import java.util.Map;

/**
 * @Author QZK
 * @Description TODO
 * @Date 2022-12-08-09:06
 * @Version 1.0
 */
public class MyHttpUtil {

    //参数类型-Form
    public static final String PARAM_TYPE_FORM = "Form";
    //参数类型-Json
    public static final String PARAM_TYPE_JSON = "Json";

    /**
     * get请求
     * @param url
     * @param params
     * @return
     */
    public static String get(String url, Map<String,Object> params) throws Exception {

        return request(url, Method.GET, params);
    }

    /**
     * post请求-JSON
     * @param url
     * @param params
     * @return
     */
    public static String post(String url, String params) throws Exception{
        return request(url, Method.POST, params);
    }

    /**
     * post请求-表单
     * @param url
     * @param params
     * @return
     */
    public static String post(String url, Map<String,Object> params) throws Exception {
        return request(url, Method.POST, params);
    }

    /**
     * delete请求-JSON
     * @param url
     * @param params
     * @return
     */
    public static String delete(String url, String params) throws Exception{
        return request(url, Method.DELETE, params);
    }

    /**
     * delete请求-表单
     * @param url
     * @param params
     * @return
     */
    public static String delete(String url, Map<String,Object> params) throws Exception{
        return request(url, Method.DELETE, params);
    }

    /**
     * put请求
     * @param url
     * @param params
     * @return
     */
    public static String put(String url, String params) throws Exception{
        return request(url, Method.PUT, params);
    }

    /**
     * put请求-表单
     * @param url
     * @param params
     * @return
     */
    public static String put(String url, Map<String,Object> params) throws Exception {
        return request(url, Method.PUT, params);
    }

    /**
     * 发送请求 -表单
     * @return
     */
    private static String request(String url, Method method, Map<String,Object> params) throws Exception {
        HttpRequest request = null;
        HttpResponse response = null;
        String body = "";
        try {
            if(StringUtils.isEmpty(url)){
                throw new HttpTimeoutException("请求URL【"+url+"】，不能为空！");
            }
            //构建Request
            request = HttpUtil.createRequest(method, url);
            //发送请求
            try {
                response = request.form(params).timeout(HttpGlobalConfig.getTimeout()).execute();
            } catch (Exception e) {
                throw new HttpTimeoutException("发送HTTP请求失败，URL【"+url+"】，错误信息："+e.getMessage());
            }
            // 判断是否请求成功
            if(!response.isOk()){
                HttpCodeErrorException exception = new HttpCodeErrorException("发送HTTP请求失败，URL【" + url + "】返回状态码【" + response.getStatus() + "】" );
                exception.setRequestResult(response.body());
                throw exception;
            }
            body = response.body();
        } catch (Exception e){
            throw  HttpException.handleException(url,method.name(), params == null ? "" : JSONObject.toJSONString(params),PARAM_TYPE_FORM,e);
        }
        return body;
    }

    /**
     * 发送请求 -JSON
     * @param url
     * @param method
     * @param params
     * @return
     */
    private static String request(String url, Method method, String params) throws HttpException {
        HttpRequest request = null;
        HttpResponse response = null;
        String body = "";
        try {
            if(StringUtils.isEmpty(url)){
                throw new HttpTimeoutException("请求URL【"+url+"】，不能为空！");
            }
            //构建Request
            request = HttpUtil.createRequest(method, url);

            //发送请求
            try {
                response = request.timeout(HttpGlobalConfig.getTimeout()).body(params).execute();
            } catch (Exception e) {
                throw new HttpTimeoutException("发送HTTP请求失败，URL【"+url+"】，错误信息："+e.getMessage());
            }
            // 判断是否请求成功
            if(!response.isOk()){
                throw new HttpCodeErrorException("发送HTTP请求失败，URL【"+url+"】返回状态码【"+response.getStatus()+"】，服务器返回数据："+response.body());
            }
            body = response.body();
        } catch (Exception e){
            throw  HttpException.handleException(url,method.name(), params == null ? "" : JSONObject.toJSONString(params),PARAM_TYPE_JSON,e);
        }
        return body;
    }

    public static void main(String[] args) throws Exception {
        String url = "http://127.0.0.1:8001/api/deviceToMes/deviceHeartBeat";
        String params = "{\n" +
                "  \"deviceCode\": \"RR333\",\n" +
                "  \"isOnline\": \"1\",\n" +
                "  \"operator\": \"admin\",\n" +
                "  \"timestamp\": \"2022-04-25 10:22:43\"\n" +
                "}";
        String post = post(url, params);
        System.out.println(post);
    }
}
